<?php

namespace backend\services\order;

use backend\extensions\ApiBaseService;

use common\services\order\OrderCommonService;
use backend\models\order\Order;
/**
 * Desc 订单管理服务类
 * @author WMX
 */
class OrderService extends ApiBaseService
{

    /**
     * 列表——获取订单
     * @param array $params 参数 
     * **/
    public static function getList($params)
    {
        //检索条件
        $condition = ['AND'];
        if ($params['state']) {
            $condition[] = ['=', 'o.state', $params['state']??''];
        }
        if ($params['order_sn']) {
            $condition[] = ['=', 'o.order_sn', $params['order_sn']??''];
        }
        if ($params['pay']) {
            $condition[] = ['=', 'o.pay_way', $params['pay']??''];
        }
        if ($params['phone']) {
            $condition[] = ['=', 'u.phone', $params['phone']??''];
        }
        if ($params['client']) {
            $condition[] = ['=', 'o.client', $params['client']??''];
        }
        if($params['time_range']) {
            $condition[] = ['>=', 'o.create_time', $params['time_range'][0]??''];
            $condition[] = ['<', 'o.create_time', $params['time_range'][1]??''];
        }
        
        $list = OrderCommonService::getUnionAll($condition, $params['page'], $params['page_size']);
        return $list;
    }

    // 获取订单详情
    public static function detail($params)
    {
        $data = OrderCommonService::getOrderDetail($params['order_sn']);
        return $data;
    }

    // 发货
    public static function send($params)
    {
        $data = OrderCommonService::getOrderDetail($params['order_sn']);
        if(empty($data)) {
            return self::jsonError('订单异常');
        }
        if(!($params['state'] == Order::STATE_WAIT_DELIVERY || $params['state'] == Order::STATE_WAIT_RECEIVE || $params['state'] == Order::STATE_RECEIVED)) {
            return self::jsonError('状态异常');
        }
        $params['state'] = $params['state'];
        $condition = ['order_sn' => $params['order_sn']];
        unset($params['order_sn']);
        if (Order::updateData($params, $condition) === false) {
            return self::jsonError('更新失败');
        }
        return self::jsonSuccess();
    }

    // 小票打印
    public static function printer($params)
    {
        try {
            $data = OrderCommonService::getOrderDetail($params['order_sn']);

            if (!empty($data)) {
                list($code, $msg) = OrderCommonService::printerOrder($data);
                list($code2, $msg2) = OrderCommonService::printGoodsTag($data);
                if($code != 0) {
                    throw new \Exception('小票机异常：'.$msg);
                }
                if($code2 != 0) {
                    throw new \Exception('标签机异常：'.$msg2);
                }
            }
            return self::jsonSuccess($data);
        } catch (\Exception $exc) {
            return self::jsonError($exc->getMessage());
        }
    }

}
